package cn.moonspace.flowerowner.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.moonspace.common.util.Md5Util;
import cn.moonspace.flowerowner.entities.User;
import cn.moonspace.flowerowner.form.LoginForm;
import cn.moonspace.flowerowner.form.RegisterForm;
import cn.moonspace.flowerowner.service.UserService;


@Controller
public class UserController extends BaseController {
	
	@RequestMapping(value = "/user/register",method = RequestMethod.GET) 
	public String registerForm(ModelMap modelMap) {
		modelMap.addAttribute("registerUserForm", new RegisterForm());
		return "register";
	}
	
	@RequestMapping(value = "/user/register",method = RequestMethod.POST) 
	public @ResponseBody Object postRegisterForm(
			@Valid @ModelAttribute("registerForm") RegisterForm registerForm, Errors errors, HttpSession session)  {
		JSONObject result = new JSONObject();
		JSONArray list = new JSONArray();
		Map<String, String> errorMap = new HashMap<String, String>();
		
		// 错误校验
		if(errors.hasErrors()) {
			for(FieldError error : errors.getFieldErrors()) {
				errorMap.put("field", error.getField() + "Help");
				errorMap.put("message", error.getDefaultMessage());
				list.add(errorMap);
			}
			result.put("error", list);
			return result;
		} else {
			if(userRepository.findByUsername(registerForm.getUsername()) != null) {
				errorMap.put("field", "usernameHelp");
				errorMap.put("message", "该用户名已被注册");
				list.add(errorMap);
				result.put("error", list);
				return result;
			} 
			if(!registerForm.getPassword().equals(registerForm.getRepassword())) {
				errorMap.put("field", "passwordHelp");
				errorMap.put("message", "两次密码输入不一致");
				list.add(errorMap);
				result.put("error", list);
				return result;
			}  
		}	
		
		// 没有任何错误，注册成功
		User user = new User();
		user.setUsername(registerForm.getUsername());
		user.setPassword(Md5Util.MD5(registerForm.getPassword()));
		userRepository.save(user);
		result.put("message", "success");
		session.setAttribute("user", user);
		return result;
	}
	
	@RequestMapping(value="/user/login",method=RequestMethod.POST) 
	public @ResponseBody Object postLogin(
			@Valid @ModelAttribute("loginForm") LoginForm loginForm, 
			Errors errors, HttpSession session) {
		JSONObject result = new JSONObject();
		JSONArray list = new JSONArray();
		Map<String, String> errorMap = new HashMap<String, String>();
		
		// 错误校验
		if(errors.hasErrors()) {
			for(FieldError error : errors.getFieldErrors()) {
				errorMap.put("field", error.getField() + "Help");
				errorMap.put("message", error.getDefaultMessage());
				list.add(errorMap);
			}
			result.put("error", list);
			return result;
		}
		
		switch (userService.login(loginForm)) {
		case UserService.USERNAME_NOT_FOUND:
			errorMap.put("field", "usernameHelp");
			errorMap.put("message", "用户名不存在");
			list.add(errorMap);
			result.put("error", list);
			return result;
		case UserService.PASSWORD_ERROR:
			errorMap.put("field", "passwordHelp");
			errorMap.put("message", "密码错误");
			list.add(errorMap);
			result.put("error", list);
			return result;
		default:
			// 登录成功
			result.put("message", "success");
			session.setAttribute("user", userRepository.findByUsername(loginForm.getUsername()));
			return result;
		}
	}
	
	@RequestMapping(value="/user/logout",method=RequestMethod.GET) 
	public String logout(HttpSession session) {
		session.removeAttribute("user");
		return "redirect:/index";
	}
	
}
